#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:    御风
# @Mail:      zhong.yufeng@foxmail.com
# @Time:      2022/4/12 1:30


import time
from flask import request, current_app as app
from flask_cors import cross_origin
from modules.admin import AdminDataBase
from utils.result import ApiResult
from utils.session.session import Session
from .admin import route

USE_CAPTCHA = False


# http://127.0.0.1:9001/admin/login
@route.route(r"/login", methods=["GET"], strict_slashes=False)
@cross_origin()
def apiLogin():
    """
    管理登录处理
    """
    session = Session.get()
    captcha = ""
    now = int(time.time())

    try:
        account = request.args.get("user", "", str).strip()
        password = request.args.get("pass", "", str).strip()
        if account == "":
            raise ValueError("帐号不能为空")
        if password == "":
            raise ValueError("密码不能为空")
        if USE_CAPTCHA:
            captcha = request.args.get("code", "", str).strip()
            if captcha == "":
                raise ValueError("验证码不能为空")
    except ValueError as e:
        return ApiResult.error(101001, msg=str(e))
    except Exception:
        return ApiResult.error(101002, msg="参数有误")

    if USE_CAPTCHA:
        captchaCode = session.get("adminCaptchaCode", "")
        captchaTime = session.get("adminCaptchaTime", 0)
        session.pop("adminCaptchaCode", None)
        session.pop("adminCaptchaTime", None)
        Session.set(session)
        if not captchaCode or captchaCode == "":
            return ApiResult.error(101003, msg="验证码错误")
        if not captchaTime or (now - captchaTime) > (60 * 30):
            return ApiResult.error(101004, msg="验证码错误")
        if captchaCode.lower() != captcha.lower():
            return ApiResult.error(101005, msg="验证码错误")

    result = { }
    try:
        db = AdminDataBase()
        info = db.query(account, password)
        if not info:
            return ApiResult.error(101006, msg="登录失败")
        if not info.get("valid"):
            return ApiResult.error(101007, msg="帐号禁止登录")
        adminId = info.get("id", None)
        if not adminId:
            return ApiResult.error(101008, msg="帐号信息异常")
        session["adminId"] = adminId
        session["adminAccount"] = account
        session["adminPassword"] = password
        session["adminLoginTime"] = now
        Session.set(session)
        result["id"] = adminId
        result["account"] = account
        result["session"] = Session.serializer()
    except ValueError as e:
        return ApiResult.error(101009, msg=str(e))
    except InternalError as e:
        app.logger.error(f"[数据库] {e}")
        return ApiResult.error(101010, msg="失败")
    except Exception as e:
        app.logger.error(f"[错误] {e}")
        return ApiResult.error(101011, msg="失败")
    return ApiResult.success(result, msg="成功")
